package com.fingard.dsp.bank.directbank.hxb01;


import java.text.MessageFormat;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.util.TransIDHelper;


public class HXB01Base extends DirectBase implements ITcpClient {
	
	private static TransIDHelper idHelper = new TransIDHelper(1, 999);
	
	protected String getQryTransID(){
		Date tmpDateNow = new Date();
		return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
	}
	protected String[] sendToBank(String p_reqStr) throws Exception{
		
		String[] retStr = new String[]{"",""};
			
		WriteBankLogLn("2.提交银行的地址："+bankFront.serverIP+":"+bankFront.serverPort);
		
		//发送银行前置
		TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP,Integer.parseInt(bankFront.serverPort),this);
		String tmpCharset = "GBK";
		byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);
		
		WriteBankLogStep2(p_reqStr);
		TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
		retStr[0] = tmpReceiver.connState;
		if(tmpReceiver.recBytes != null){
			retStr[1] = new String(tmpReceiver.recBytes,0, tmpReceiver.readedLength, tmpCharset);
			WriteBankLogStep3(retStr[1]);
		}
		else{
			retStr[1] = tmpReceiver.getConnMsg();
		}
		if(!tmpReceiver.isCompleted){
			WriteBankLogLn(tmpReceiver.getConnMsg());
		}
        return retStr;
	}
	
	public void getContentLength(TcpReceiver p_receiver) throws Exception{
		if(p_receiver.contentLength == -1){
			String tmpCharset = "GBK";
			String tmpRecNow = new String(p_receiver.recBytes,0, p_receiver.readedLength, tmpCharset);
			if(tmpRecNow.indexOf("@@@@") >= 0){
				p_receiver.contentLength = p_receiver.readedLength;
				p_receiver.contentStartIndex = 0;
			}
		}
	}

	/**
	 * 业务类型转换
	 * @param busiType:业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
	 * @param operType:1-申请 2-签收 3-驳回 4-撤销
	 * @return
	 * @throws Exception
	 */
	protected String billTypeChange(String busiType,String operType) throws Exception{
		String type="";
		if("1".equals(operType)){
			switch (Integer.parseInt(busiType)){
				case 1:type="BA";break;
				case 2:type="BAA";break;
				case 3:type="BS";break;
				case 4:type="BE";break;
				case 5:type="BP";break;
				case 10:type="BD";break;
				case 12:type="BC";break;
				default:type="";break;
			}
		}else if("2".equals(operType)){
			type="RP";
		}else if("3".equals(operType)){
			type="RP";
		}else if("4".equals(operType)){
			type="CS";
		}
		if("".equals(type)){
			throw new Exception("华夏银行暂不支持此操作，busiType="+busiType+";operType="+operType);
		}
		return type;
	}

	/**
	 * 业务类型转换
	 * @param busiType:业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
	 * @param recourseType:追索类型 1-拒付追索 2-非拒付追索
	 * @return
	 * @throws Exception
	 */
	protected String tradeTypeChange(String busiType,String recourseType) throws Exception{
		String type="";
		switch (Integer.parseInt(busiType)){
			case 1:type="";break;//出票
			case 2:type="";break;//提示承兑
			case 4:type="0";break;//可背书
			case 9:type="1";break;//可背书保证
			case 10:type="2";break;//可贴现
			case 5:type="3";break;//可质押
			case 6:type="3";break;//解质押
			case 12:type="4";break;//可提示付款
			case 13:
				if("1".equals(recourseType)){
					type="5";//可拒付追索
				}else {
					type="6";//可非拒付追索
				}
				break;
			case 14:type="7";break;//可同意清偿
			case 3:type="8";break;//可提示收票（新增）
			//case 1:type="9";break;//待照票查询（新增）
			default:throw new Exception("暂不支持此操作："+busiType);
		}
		return type;
	}

	/**
	 * 查询票据状态
	 * @param billNo：电票编号
	 * @param billType：电票类型
	 * @param actNum：帐号
	 * @return
	 * @throws Exception
	 */
	protected String[] getBillStatus(String billNo,String billType,String actNum,String count) throws Exception{
		WriteBankLogLn("查询"+billNo+"票据状态start");
		String[] billStatus=new String[]{"",""};
		//请求字段名
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < 21; i++) {
			stringBuilder.append("{" + i + "}#");
		}
		stringBuilder.append("@@@@");
		//请求字段值
		String[] body = new String[21];
		body[0] = "B308001";//交易代码
		body[1] = billNo;//电子票据号码
		body[2] = billNo;//序号
		body[3] = getBankConfig().getMapValueByKey("billTypeMapping", billType);//票据类别
		body[4] = "";
		body[5] = count;//业务种类
		body[6] = bankFront.org;//客户号
		body[7] = actNum;//客户账号
		body[8] = "";//协议号码
		body[9] = "";//出票人姓名
		body[10] = "";//出票起始日
		body[11] = "";//出票截止日
		body[12] = "";//到期起始日
		body[13] = "";//到期截止日
		body[14] = "";//票据状态
		body[15] = "";//金额上线
		body[16] = "";//金额下线
		body[17] = "";//批次号码
		body[18] = "";//电票流水号码
		body[19] = "1";//页码
		body[20] = getBankConfig().getValueAsString("pageSize");//每页条数
		//请求报文
		String sendInfo = MessageFormat.format(stringBuilder.toString(), body[0], body[1], body[2], body[3], body[4], body[5], body[6], body[7]
				, body[8], body[9], body[10], body[11], body[12], body[13], body[14], body[15], body[16], body[17], body[18], body[19], body[20]);
		//请求银行
		String[] tmpStrRet = sendToBank(sendInfo);
		if (tmpStrRet[0].length() == 0) {
			//返回码
			String[] resultArr = tmpStrRet[1].trim().replaceAll("@","").replaceAll("\r","")
					.replaceAll("\n","").split("#");
			if ("000000".equals(resultArr[0])) {
				if(Integer.valueOf(resultArr[1])==1){
					String[] content=resultArr[2].replaceAll(" ","").split("\\|");
					billStatus[0]=content[6];
					billStatus[1]=content[16];
				}
			}
		}
		WriteBankLogLn("查询"+billNo+"票据状态end，票据状态为："+billStatus[1]+";背书转让标识："+billStatus[0]);
		return billStatus;
	}

	/**
	 * 电票操作业务流水号
	 * @return
	 */
	protected String getQryTransID2(){
		return Format.DateTime15Year2Format.format(new Date());
	}

	/**
	 * 票据背面信息查询业务转换
	 * 交易类型代码 2  承兑 3  收票 4  撤票 10  背书转让 11  贴现 12  回购式贴现赎回 13  转贴现 15  再贴现   17  保证     22  追索 23  追索同意清偿
	 * @return
	 */
	protected String getTransCode(String billType){
		String transCode="";
		if(!StringHelper.isNullOrEmpty(billType)){
			switch (Integer.parseInt(billType)){
				case 100006:transCode="10";break;//背书
				case 110106:transCode="11";break;//买断式贴现
				case 110206:transCode="11";break;//回购式贴现
				case 120006:transCode="12";break;//回购式贴现赎回
				case 140006:transCode="14";break;//14  回购式转贴现赎回
				case 160006:transCode="16";break;//16  回购式再贴现赎回
				case 250006:transCode="25";break;//25  央行卖出商业汇票
				//case 020006:transCode="17";break;//
				case 180006:transCode="18";break;//18  质押
				case 190006:transCode="19";break;//19  质押解除
				//case 020006:transCode="22";break;//
				//case 020006:transCode="23";break;//
				default:transCode="";
			}
		}
		return transCode;
	}

	/**
	 * 撤回票据状态
	 * @param cancelType:撤回类型 1-承兑申请撤回 2-提示收票申请撤回 3-背书转让申请撤回 4-贴现申请撤回 5-质押申请撤回 6-（逾期）提示付款撤回
	//    7-出票保证申请撤回 8-承兑保证申请撤回  9-背书保证申请撤回 10-追索通知撤回 11-同意清偿撤回 12-解质押申请撤回
	 * @return
	 */
	protected boolean billStatus(String cancelType,String billStatus){
		boolean flag=false;
		if("3".equals(cancelType) && "100001".equals(billStatus)){//撤销背书
			flag=true;
		}else if("4".equals(cancelType) && "110101".equals(billStatus)){//贴现撤销
			flag=true;
		}else if("5".equals(cancelType) && "180001".equals(billStatus)){//质押撤销
			flag=true;
		}else if("6".equals(cancelType) && "210001".equals(billStatus)){//逾期提示付款撤销
			flag=true;
		}
		return flag;
	}

    protected  String[] sendToATS(String jsonData) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogLn("2.提交ATS的地址："+ FGBiz.dspCenter.dspSet.receiptPushServerUrl);

        //发送ATS
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(60000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        String charsetName = getCharset();
        WriteBankLogLn("3.推送给ATS的json数据"+jsonData);
        byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据"+retStr[1]);

        return retStr;
    }
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }
}
